<?php
namespace app\api\controller;

use think\Controller;
use app\index\model\VisitorModel;
use app\api\model\ChatModel;

class Base extends Controller {

    public function _initialize() {
		header('Access-Control-Allow-Origin:*');
		$param = input('post.');
		if(isset($param['api_key'])) {
			if($param['api_key'] != md5(config('api_key'))){
				echo json_encode(['code'=>-999,'msg'=>'Illegal Request']);exit;
			}else{
				$this->params = $param['params'];
			}
		}else{
			echo json_encode(['code'=>-999,'msg'=>'Illegal Request']);exit;
		}
	}

	/**
	 * [发送消息]
	 */
	public function socketSendMsg($chatRoomId='',$msg='',$send_id=0,$msg_type="") {
		$visitorModel = new VisitorModel();
		$chatModel = new ChatModel();
		// 验证 判断发送人和接收人
		$chatRoomInfo = $chatModel::where('id',$chatRoomId)->find()->toArray();
		$senderInfo = $visitorModel::where('id',$send_id)->field('id,nick_name,head')->find()->toArray();
		if(empty($senderInfo)){
			return ['code'=>0,'msg'=>'发送者不存在'];
		}
		if($chatRoomId == ''){
			return ['code'=>0,'msg'=>'请先择聊天室'];
		}
		// 接收人
		$uid_str = $chatRoomInfo['visitor_ids'];
		$uid_arr = explode(",",$uid_str);
		$user_ids = [];
		foreach($uid_arr as &$v){
			$i = explode("|",$v)[1];
			if($i != $send_id){
				$user_ids[] = $i;
			}
			$v = $chatRoomId."_".$i;
		}
		$uid_str = implode(",",$uid_arr);
		$user_ids = implode(",",$user_ids);
		// 写入文件，更新数据库
		$chatModel::startTrans();
		try{
			$savedMsg = socketMsg_encode($send_id,$senderInfo,$msg);
			$chatFilePath = APP_PATH."../public/upload/chatfile/".$chatRoomId.".chatfile";
			if(!file_exists($chatFilePath)){
				creatChatFile($chatRoomId);
			}
			$Context = file_get_contents($chatFilePath);
			$cahtFile = fopen($chatFilePath,'w');
			fwrite($cahtFile, $Context.$savedMsg);
			fclose($cahtFile);
			$chatModel::where('id',$chatRoomId)->update([
				"last_msg" => $msg,"last_vid" => $send_id,"update_at" => time()
			]);
			$chatModel::commit();
		}catch(\Exception $e){
			$chatModel::rollback();
			return ['code'=>0,'msg'=>'聊天记录保存失败:'.$e->getMessage()];
		}
		// 发送消息
		$msgInfo = [
			"sender_id" => $send_id,
			"sender_name" => $senderInfo['nick_name'],
			"sender_head" => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].$senderInfo['head'],
			"chat_room_id" => $chatRoomId,
			"chat_room_name" => $chatRoomInfo['chat_name'],
			"msg_type" => $msg_type
		];
		$return = [
			"to_chatroom" => send_socket_msg($uid_str,$msg,$msgInfo),
			"to_desktop" => send_socket_msg($user_ids,$msg,$msgInfo)
		];
		return $return;
	}

	/**
	 * [系统消息]
	 */
	public function socket_push($uid_arr=[],$msg="",$send_id=0,$sender_info="",$msg_type="") {
		$msgInfo = [
			"sender_id" => $send_id,
			"sender_name" => $sender_info['nick_name'],
			"sender_head" => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].$sender_info['head'],
		];
		foreach($uid_arr as $v){
			send_socket_msg($v,$msg,$msgInfo);
		}
	}

	/**
	 * [个推推送]
	 */
	public function GETUI_push() {

	}
}
